package com.bindapp.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bindapp.R;
import com.bindapp.listener.ViewClickListener;
import com.bindapp.model.LoadLayoutModel;


/**
 * Created by nbzl on 2016/10/24.
 */
public class BaseFragment extends Fragment {

    protected boolean isVisible=false,isPrepared=false,isFirst=true;
    protected View baseview,contentview;
    protected FrameLayout frameLayout;
    protected LoadLayoutModel loadLayoutModel;

    protected ProgressDialog progressDialog;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        }else{
            isVisible = false;
            onInVisible();
        }
    }
    public void onVisible(){
        loaddatabase();
    }
    public void onInVisible(){

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        baseview=inflater.inflate(R.layout.fragment_base,null);
        frameLayout=(FrameLayout)baseview.findViewById(R.id.content);
        initContent(inflater);
        initLoadLayout();
        afterview();
        return baseview;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isPrepared=true;
        loaddatabase();
    }

    protected void afterview(){}
    protected void initContent(LayoutInflater inflater){}
    protected void AddBaseContentView(View view) {
        frameLayout.removeAllViews();
        frameLayout.addView(view);
    }
    public void loaddatabase(){
        if(!isPrepared || !isVisible||!isFirst) {
            return;
        }
        loaddata();
        isFirst = false;
    }
    private void initLoadLayout(){
        loadLayoutModel=new LoadLayoutModel(getActivity(),new LoadClick());
    }
    protected void loaddata(){
       // Log.e("Mytext","加载数据");

    }

    public void showProgress(String msg){
        if(progressDialog!=null){
            progressDialog=null;
        }
        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setCancelable(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }
    public void dissProgress(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    class LoadClick implements ViewClickListener {

        @Override
        public void reRequest(View view) {
            loadLayoutModel.setLoadStatus(true, "暂无数据", 0);
            loaddata();
        }
    }

}
